package com.linjian.togetherbirthday.fragment;

import android.content.Context;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.linjian.togetherbirthday.R;
import com.linjian.togetherbirthday.base.BaseFragment;
import com.linjian.togetherbirthday.contant.HttpContant;
import com.linjian.togetherbirthday.utils.HttpUtils;
import com.linjian.togetherbirthday.utils.NoticeEvent;
import com.linjian.togetherbirthday.utils.SharedPreferencesUtil;
import com.sdsmdg.tastytoast.TastyToast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class ChangePhoneFragment extends BaseFragment implements View.OnClickListener {

    private EditText newPhoneEt,codeEt;
    private TextView confirmPwdTv;
    private ImageView backIv;
    private TextView titleTv,rightTv,getCodeTv;

    private MyCountDownTimer myCountDownTimer;

    public static ChangePhoneFragment newInstance() {
        ChangePhoneFragment changePhoneFragment = new ChangePhoneFragment();
        Bundle bundle = new Bundle();
        changePhoneFragment.setArguments(bundle);
        return changePhoneFragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        EventBus.getDefault().register(this);
    }

    @Override
    protected int setView() {
        return R.layout.fragment_change_phone;
    }

    @Override
    protected void init(View view) {
        backIv = view.findViewById(R.id.layout_head_back_iv);
        titleTv = view.findViewById(R.id.layout_head_title_tv);
        rightTv = view.findViewById(R.id.layout_head_right_tv);
        newPhoneEt = view.findViewById(R.id.change_phone_et);
        codeEt = view.findViewById(R.id.change_phone_code_et);
        confirmPwdTv = view.findViewById(R.id.change_phone_tv);
        getCodeTv = view.findViewById(R.id.change_phone_get_code);
        myCountDownTimer = new MyCountDownTimer(60000, 1000);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        titleTv.setText("更换手机");
        rightTv.setVisibility(View.GONE);
        setListener();
    }

    private void setListener() {
        backIv.setOnClickListener(this);
        confirmPwdTv.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.layout_head_back_iv:
                getActivity().getSupportFragmentManager().popBackStack();
                break;
            case R.id.change_phone_get_code:
                if (TextUtils.isEmpty(newPhoneEt.getText())){
                    TastyToast.makeText(getActivity(),"手机号不能为空",TastyToast.LENGTH_SHORT,TastyToast.WARNING).show();
                }else {
                    getChangePhoneCode(2, newPhoneEt.getText().toString());
                    try {
                        myCountDownTimer.start();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;
            case R.id.change_phone_tv:
                if (TextUtils.isEmpty(newPhoneEt.getText())||TextUtils.isEmpty(codeEt.getText())){
                    TastyToast.makeText(getActivity(),"选项不能为空",TastyToast.LENGTH_SHORT,TastyToast.WARNING).show();
                }else {
                    httpChangePhone(newPhoneEt.getText().toString(),codeEt.getText().toString());
                }
                break;
        }
    }

    /**
     * 修改密码接口
     */
    private void httpChangePhone(String phone, String code){
        Map<String,Object> map = new HashMap<>();
        map.put("phone",phone);
        map.put("code",code);
        HttpUtils.PutCookie(HttpContant.URL + HttpContant.ChangePwd
                , "SESSION=" + String.valueOf(SharedPreferencesUtil.get(getActivity(), "Cookie", ""))
                , map
                , new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        EventBus.getDefault().post(new NoticeEvent("requestFail"));
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        EventBus.getDefault().post(new NoticeEvent("changePasswrod",response.body().string()));
                    }
                });
    }

    /**
     * 更换手机接口
     */
    private void getChangePhoneCode(int type,String phone){
        Map<String,Object> map = new HashMap<>();
        map.put("type",2);
        map.put("phone",phone);
        HttpUtils.PutCookie(HttpContant.URL + HttpContant.ChangePhone
                , "SESSION=" + String.valueOf(SharedPreferencesUtil.get(getActivity(), "Cookie", ""))
                , map
                , new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        EventBus.getDefault().post(new NoticeEvent("requestFail"));
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        EventBus.getDefault().post(new NoticeEvent("changePhone",response.body().string()));
                    }
                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMsg(NoticeEvent event){
        switch (event.getCls()){
            case "requestFail":
                TastyToast.makeText(getActivity(),"请求失败",TastyToast.LENGTH_SHORT,TastyToast.ERROR).show();
                break;
            case "changeGetCode":
                try {
                    JSONObject object = new JSONObject(event.getData().toString());
                    if (object.getInt("code") == 200){
                        TastyToast.makeText(getActivity(),"验证码已发送",TastyToast.LENGTH_SHORT,TastyToast.SUCCESS).show();
                    }else {
                        TastyToast.makeText(getActivity(),object.getString("msg"),TastyToast.LENGTH_SHORT,TastyToast.ERROR).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
            case "changePhone":
                try {
                    JSONObject object = new JSONObject(event.getData().toString());
                    if (object.getInt("code") == 200){
                        TastyToast.makeText(getActivity(),object.getString("data"),TastyToast.LENGTH_SHORT,TastyToast.SUCCESS).show();
                        getActivity().getSupportFragmentManager().popBackStack();
                    }else {
                        TastyToast.makeText(getActivity(),object.getString("msg"),TastyToast.LENGTH_SHORT,TastyToast.ERROR).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    //倒计时函数
    private class MyCountDownTimer extends CountDownTimer {

        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        //计时过程
        @Override
        public void onTick(long l) {
            //防止计时过程中重复点击
            getCodeTv.setClickable(false);
            getCodeTv.setText(l / 1000 + "秒");

        }

        //计时完毕的方法
        @Override
        public void onFinish() {
            //重新给Button设置文字
            getCodeTv.setText("重新获取");
            //设置可点击
            getCodeTv.setClickable(true);
        }
    }
}
